package com.bw.home.ui

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.bw.home.adpter.RecommendAdapter
import com.bw.home.databinding.FragmentHomeDetailRecommendBinding
import com.bw.home.intent.SimpleVideoIntent
import com.bw.home.entity.SimpleVideoEntity
import com.bw.home.state.SimpleVideoState
import com.bw.home.viewmodel.SimpleVideoViewModel
import com.bw.lib_mvi.view.BaseMVIFragment
import kotlinx.coroutines.launch


class HomeDetailRecommendFragment : BaseMVIFragment() {
    lateinit var binding: FragmentHomeDetailRecommendBinding
    lateinit var viewModel: SimpleVideoViewModel
    lateinit var adapter: RecommendAdapter
    var dataSource: MutableList<SimpleVideoEntity> = mutableListOf()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentHomeDetailRecommendBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun initView() {
        super.initView()
        adapter = RecommendAdapter(requireContext(), dataSource)
        binding.rvRecommendHomeDetail.adapter = adapter
        binding.rvRecommendHomeDetail.layoutManager = GridLayoutManager(requireContext(), 2)
    }

    override fun generateViewModel() {
        viewModel = ViewModelProvider(requireActivity()).get(SimpleVideoViewModel::class.java)
        loadRecommendVideo()
    }

    private fun loadRecommendVideo() {
        lifecycleScope.launchWhenResumed {
            viewModel.intents.send(SimpleVideoIntent.getRecommendVideoIntent(1, 12))
        }
    }

    override fun handlerState() {
        lifecycleScope.launch {
            viewModel.state.collect {
                when (it) {

                    is SimpleVideoState.getRecommendVideoState -> {
                        dataSource.clear()
                        dataSource.addAll(it.data)
                        adapter.notifyDataSetChanged()
                    }

                    is SimpleVideoState.Failed -> {
                        Log.d("TagA", "获取数据失败: $it")
                    }

                    else -> {}
                }
            }
        }
    }

}